package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.AttrTrashEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.StageTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.SaasParticularAttributePoJo;
import com.xbongbong.paas.help.menu.InitCrmMenuHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.model.AttrTrashModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.FieldAttrEntityForDecisionInfo;
import com.xbongbong.paas.pojo.dto.FormUpdateDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.vo.FormEntityGetVO;
import com.xbongbong.paas.service.FieldIndexService;
import com.xbongbong.paas.service.dynamic.crm.strategy.CompetitorDynamicStrategy;
import com.xbongbong.paas.service.dynamic.crm.strategy.DynamicStrategyFactory;
import com.xbongbong.paas.service.log.crm.operation.CompetitorAnalysisOperationLogHandler;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.interfaces.logger.OperationLogFactory;
import com.xbongbong.pro.competitor.pojo.CompetitorAnalysisSearchListItemPojo;
import com.xbongbong.pro.competitor.pojo.dto.CompetitorAnalysisDeleteDTO;
import com.xbongbong.pro.competitor.pojo.dto.CompetitorAnalysisDetailDTO;
import com.xbongbong.pro.competitor.pojo.dto.CompetitorAnalysisFormGetDTO;
import com.xbongbong.pro.competitor.pojo.dto.CompetitorAnalysisFormSaveDTO;
import com.xbongbong.pro.competitor.pojo.dto.CompetitorAnalysisListDTO;
import com.xbongbong.pro.competitor.pojo.dto.CompetitorAnalysisSearchListDTO;
import com.xbongbong.pro.competitor.pojo.dto.CompetitorAnalysisSwotGetDTO;
import com.xbongbong.pro.competitor.pojo.dto.CompetitorAnalysisSwotUpdateDTO;
import com.xbongbong.pro.competitor.pojo.dto.CompetitorAnalysisUpdateDTO;
import com.xbongbong.pro.competitor.pojo.dto.CompetitorAnalysisUpdateGetDTO;
import com.xbongbong.pro.competitor.pojo.dto.log.CompetitorAnalysisExplainSaveLogDTO;
import com.xbongbong.pro.competitor.pojo.dto.log.CompetitorAnalysisUpdateLogDTO;
import com.xbongbong.pro.competitor.pojo.dto.log.LinkCompetitorLogDTO;
import com.xbongbong.pro.competitor.pojo.dto.log.SwotUpdateLogDTO;
import com.xbongbong.pro.competitor.pojo.vo.CompetitorAnalysisDeleteVO;
import com.xbongbong.pro.competitor.pojo.vo.CompetitorAnalysisDetailVO;
import com.xbongbong.pro.competitor.pojo.vo.CompetitorAnalysisFormGetVO;
import com.xbongbong.pro.competitor.pojo.vo.CompetitorAnalysisFormSaveVO;
import com.xbongbong.pro.competitor.pojo.vo.CompetitorAnalysisListVO;
import com.xbongbong.pro.competitor.pojo.vo.CompetitorAnalysisSearchListVO;
import com.xbongbong.pro.competitor.pojo.vo.CompetitorAnalysisSwotGetVO;
import com.xbongbong.pro.competitor.pojo.vo.CompetitorAnalysisSwotUpdateVO;
import com.xbongbong.pro.competitor.pojo.vo.CompetitorAnalysisUpdateGetVO;
import com.xbongbong.pro.competitor.pojo.vo.CompetitorAnalysisUpdateVO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicLinkOpportunityDTO;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.WorkReportErrorCodeEnum;
import com.xbongbong.pro.form.pojo.FieldEsIndexPoJo;
import com.xbongbong.pro.formdata.pojo.AfterSavePojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainInLinkItemDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.SaleStageEntity;
import com.xbongbong.saas.domain.entity.competitor.CompetitorAnalysisEntity;
import com.xbongbong.saas.domain.entity.competitor.CompetitorEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.domain.entity.ext.OpportunityEntityExt;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.CompetitorErrorCodeEnum;
import com.xbongbong.saas.enums.KnowledgeErrorCodeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CompetitorAnalysisEnum;
import com.xbongbong.saas.enums.business.CompetitorEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.model.CompetitorAnalysisModel;
import com.xbongbong.saas.model.CompetitorModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.model.SaleStageModel;
import com.xbongbong.saas.service.CompetitorAnalysisService;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: yingjf
 * @date: 2022/8/17 11:01
 * @description:竞争对手分析业务
 */
@Slf4j
@Service("competitorAnalysisService")
public class CompetitorAnalysisServiceImpl implements CompetitorAnalysisService {
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private InitCrmMenuHelp initCrmMenuHelp;
    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private CompetitorAnalysisModel competitorAnalysisModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private CompetitorModel competitorModel;
    @Resource
    private SaleStageModel saleStageModel;
    @Resource
    private DynamicStrategyFactory dynamicStrategyFactory;
    @Resource
    private AttrTrashModel attrTrashModel;
    @Resource
    private FieldIndexService fieldIndexService;
    @Resource
    private OperationLogFactory operationLogFactory;
    @Resource
    private LogHelp logHelp;
    @Resource
    private MongoLogHelp mongoLogHelp;


    @Override
    public void beforeSave(ValidateDataDTO validateDataDTO) throws XbbException {
        String corpid = validateDataDTO.getCorpid();
        JSONObject data = validateDataDTO.getData();
        Long competitorId = data.getJSONArray(CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr()).getJSONObject(0).getLong(StringConstant.ID);
        Long customerId = data.getJSONArray(CompetitorAnalysisEnum.CUSTOMER_NAME_HIDE.getAttr()).getJSONObject(0).getLong(StringConstant.ID);
        Long opportunityId = data.getJSONArray(CompetitorAnalysisEnum.OPPORTUNITY_NAME_HIDE.getAttr()).getJSONObject(0).getLong(StringConstant.ID);
        Map<String,Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("oppotunityId",opportunityId);
        params.put("competitorId",competitorId);
        params.put("customerId",customerId);
        params.put("corpid",corpid);
        params.put("del",0);
        List<CompetitorAnalysisEntity> competitorAnalysisEntityList = competitorAnalysisModel.findEntitys(params);
        if(CollectionsUtil.isNotEmpty(competitorAnalysisEntityList) && competitorAnalysisEntityList.size()>0){
            // 机会和竞争对手已经关联
            throw new XbbException(CompetitorErrorCodeEnum.API_ERROR_330001.getCode(), CompetitorErrorCodeEnum.API_ERROR_330001.getMsg());
        }
        params.clear();
        params.put("oppotunityId",opportunityId);
        params.put("corpid",corpid);
        params.put("del",0);
        Integer count = competitorAnalysisModel.getEntitysCount(params);
        if(count>=50){
            throw new XbbException(CompetitorErrorCodeEnum.API_ERROR_330002.getCode(), CompetitorErrorCodeEnum.API_ERROR_330002.getMsg());
        }

    }

    @Override
    public AfterSavePojo afterSave(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        String corpid = saasFormSaveDTO.getCorpid();
        JSONObject newData = saasFormSaveDTO.getNewData();

        Long competitorId = newData.getJSONArray(CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr()).getJSONObject(0).getLong(StringConstant.ID);
        Long customerId = newData.getJSONArray(CompetitorAnalysisEnum.CUSTOMER_NAME_HIDE.getAttr()).getJSONObject(0).getLong(StringConstant.ID);
        Long opportunityId = newData.getJSONArray(CompetitorAnalysisEnum.OPPORTUNITY_NAME_HIDE.getAttr()).getJSONObject(0).getLong(StringConstant.ID);
        String competitorName = newData.getJSONArray(CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr()).getJSONObject(0).getString("name");

        OpportunityEntityExt opportunityEntityExt = opportunityModel.getByKey(opportunityId, corpid);

        JSONObject opportunityEntityExtData = opportunityEntityExt.getData();
        JSONArray linkCompetitorArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(opportunityEntityExtData, SalesOpportunityEnum.LINK_COMPETITOR.getAttr(), new JSONArray());
        JSONArray linkCompetitorNameArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(opportunityEntityExtData, SalesOpportunityEnum.LINK_COMPETITOR_LINK_TEXT.getAttr(), new JSONArray());


        if(!linkCompetitorArray.contains(competitorId)){
            linkCompetitorArray.add(competitorId);
            linkCompetitorNameArray.add(competitorName);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(SalesOpportunityEnum.LINK_COMPETITOR.getAttr(), linkCompetitorArray);
            jsonObject.put(SalesOpportunityEnum.LINK_COMPETITOR_LINK_TEXT.getAttr(), linkCompetitorNameArray);
            UpdateDataEntity updateData = ExplainUtil.getUpdateData(opportunityId, jsonObject, corpid);
            opportunityModel.updateBatch(Collections.singletonList(updateData), corpid);
        }
        return null;
    }

    @Override
    public CompetitorAnalysisFormGetVO formGet(CompetitorAnalysisFormGetDTO competitorAnalysisFormGetDTO) throws XbbException {
        CompetitorAnalysisFormGetVO competitorAnalysisFormGetVO = new CompetitorAnalysisFormGetVO();
        String corpid = competitorAnalysisFormGetDTO.getCorpid();
        try {
            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode(), corpid);
            if (Objects.isNull(paasFormEntityExt)) {
                initCrmMenuHelp.setCompetitorAnalysisFormAndExplain(competitorAnalysisFormGetDTO.getAppId(), corpid, null);
                paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode(), corpid);
            }
            if (Objects.equals(paasFormEntityExt.getDel(),DelEnum.DELETE.getDel())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            // 查看表单字段描述信息
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(paasFormEntityExt.getId(), corpid);

            if (Objects.isNull(paasFormExplainEntity) || Objects.equals(paasFormExplainEntity.getDel(), DelEnum.DELETE.getDel())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            List<FieldAttrEntityForDecisionInfo> explainList =  JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntityForDecisionInfo.class);

            competitorAnalysisFormGetVO.setBusinessType(competitorAnalysisFormGetDTO.getBusinessType());
            FormEntityGetVO formEntityGetVO = new FormEntityGetVO();
            BeanUtils.copyProperties(paasFormEntityExt, formEntityGetVO);
            competitorAnalysisFormGetVO.setAppId(competitorAnalysisFormGetDTO.getAppId());
            competitorAnalysisFormGetVO.setFormAttr(formEntityGetVO);
            competitorAnalysisFormGetVO.setFormId(paasFormEntityExt.getId());
            competitorAnalysisFormGetVO.setExplainList(explainList);
            competitorAnalysisFormGetVO.setFormExplainId(paasFormExplainEntity.getId());

            // 国际化白名单
            CompanyConfigEntity entity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.I18N_WHITE.getAlias(), PaasConstant.DEFAULT_DATA_CORPID);
            String value = CompanyConfigEnum.I18N_WHITE.getValue();
            if (Objects.nonNull(entity)) {
                value = entity.getConfigValue();
            }
            List<String> whiteList = JsonHelperUtil.parseArray(value, String.class);
            boolean flag = CollectionsUtil.isNotEmpty(whiteList) && whiteList.contains(corpid);
            competitorAnalysisFormGetVO.setMultiLang(flag);

            // 字段回收站
            Map<String, Object> param = new HashMap<>();
            param.put("corpid", corpid);
            param.put("businessType", XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode());
            param.put("recover", 0);
            param.put("del", 0);
            List<AttrTrashEntity> attrTrashEntityList = attrTrashModel.findEntitys(param);
            Set<String> trashList = new HashSet<>();
            attrTrashEntityList.forEach(v -> trashList.add(v.getAttr()));
            competitorAnalysisFormGetVO.setTrashList(trashList);

            Map<String, Map<String, FieldEsIndexPoJo>> esIndexMap = fieldIndexService.getFieldIndexNum(corpid, paasFormEntityExt.getSaasMark(), paasFormEntityExt.getBusinessType(), paasFormEntityExt.getDistributorMark(), paasFormEntityExt.getId());
            competitorAnalysisFormGetVO.setFieldMap(esIndexMap.get("field"));
            competitorAnalysisFormGetVO.setSubFieldMap(esIndexMap.get("subField"));
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            log.error("paasForm数据库查询出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return competitorAnalysisFormGetVO;
    }

    @Override
    public CompetitorAnalysisFormSaveVO formSave(CompetitorAnalysisFormSaveDTO competitorAnalysisFormSaveDTO) throws XbbException {
        CompetitorAnalysisFormSaveVO competitorAnalysisFormSaveVO = new CompetitorAnalysisFormSaveVO();
        try {
            List<FieldAttrEntityForDecisionInfo> explainList = competitorAnalysisFormSaveDTO.getExplainList();
            String corpid = competitorAnalysisFormSaveDTO.getCorpid();
            if (CollectionUtils.isEmpty(explainList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.EXPLAIN_NOT_EMPTY);
            }
            PaasFormExplainEntity explainEntity = paasFormExplainModel.getByKey(competitorAnalysisFormSaveDTO.getFormExplainId().intValue(), corpid);
            if (explainEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            // 校验explain规则
            FormUpdateDTO formUpdateDTO = new FormUpdateDTO();
            BeanUtil.copyProperties(competitorAnalysisFormSaveDTO, formUpdateDTO);
            //validateAttrRule(formUpdateDTO);

            PaasFormExplainEntity paasFormExplainEntity = new PaasFormExplainEntity();
            List<FieldAttrEntityForDecisionInfo> explains = new ArrayList<>();
            for (int i = 0; i < explainList.size(); i++) {
                FieldAttrEntityForDecisionInfo fieldAttrEntity = explainList.get(i);
                fieldAttrEntity.setSort(i);

                explains.add(fieldAttrEntity);
            }

            paasFormExplainEntity.setExplains(JSONArray.toJSONString(explains));
            paasFormExplainEntity.setCorpid(corpid);
            paasFormExplainEntity.setId(formUpdateDTO.getFormExplainId());
            paasFormExplainModel.update(paasFormExplainEntity);
            paasFormExplainEntity.setDistributorMark(explainEntity.getDistributorMark());

            // 日志保存
            afterSaveFormLog(competitorAnalysisFormSaveDTO,explainEntity,paasFormExplainEntity);

            // 字段回收站保存处理 参考现有逻辑
            Map<String, Object> param = new HashMap<>();
            param.put("corpid", corpid);
            param.put("businessType", XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode());
            param.put("recover", 0);
            param.put("del", DelEnum.NORMAL.getDel());
            List<AttrTrashEntity> attrTrashEntityList = attrTrashModel.findEntitys(param);
            Map<String, AttrTrashEntity> trashMap = new HashMap<>();
            attrTrashEntityList.forEach(v -> trashMap.put(v.getAttr(), v));

            Set<String> trashList = formUpdateDTO.getTrashList();
            if (Objects.nonNull(trashList)) {
                List<AttrTrashEntity> updateTrashList = new ArrayList<>();
                List<AttrTrashEntity> addTrashList = new ArrayList<>();
                for (String attr : trashList) {
                    if (trashMap.containsKey(attr)) {
                        updateTrashList.add(trashMap.get(attr));
                        trashMap.remove(attr);
                    } else {
                        addTrashList.add(new AttrTrashEntity(corpid, 0L, 0L, 0L, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode(), attr, formUpdateDTO.getUserId()));
                    }
                }
                if (addTrashList.size() > 0) {
                    attrTrashModel.insertBatch(addTrashList);
                }
                if (updateTrashList.size() > 0) {
                    attrTrashModel.updateBatch(updateTrashList, corpid);
                }
                List<Long> delIds = new ArrayList<>();
                trashMap.forEach((k, v) -> delIds.add(v.getId()));
                if (delIds.size() > 0) {
                    attrTrashModel.deleteBatch(delIds, corpid);
                }
            }
        } catch (XbbException e) {
            log.error("更新竞争对手分析表单失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        competitorAnalysisFormSaveVO.setAppId(competitorAnalysisFormSaveDTO.getAppId());
        competitorAnalysisFormSaveVO.setFormId(competitorAnalysisFormSaveDTO.getFormId());
        return competitorAnalysisFormSaveVO;
    }

    private void afterSaveFormLog(CompetitorAnalysisFormSaveDTO competitorAnalysisFormSaveDTO,PaasFormExplainEntity oldExplain,PaasFormExplainEntity newExplain){
        CompetitorAnalysisExplainSaveLogDTO logDTO = new CompetitorAnalysisExplainSaveLogDTO();
        BeanUtil.copyProperties(competitorAnalysisFormSaveDTO,logDTO);
        JSONObject oldObj = JSON.parseObject(JSON.toJSONString(oldExplain));
        JSONObject newObj = JSON.parseObject(JSON.toJSONString(newExplain));
        logDTO.setOldExplain(oldObj);
        logDTO.setNewExplain(newObj);
        CompetitorAnalysisOperationLogHandler logHandle = (CompetitorAnalysisOperationLogHandler) operationLogFactory.getOperationLogHandle(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode());
        if (Objects.nonNull(logHandle)) {
            logHandle.saveFormExplain(logDTO);
        }
    }

    @Override
    public void formatLinkAddExplain(HandlerExplainInLinkItemDTO handlerExplainInLinkItemDTO) throws XbbException {
        JSONObject linkFormData = handlerExplainInLinkItemDTO.getLinkFormData();
        Long linkDataId = handlerExplainInLinkItemDTO.getLinkDataId();
        List<FieldAttrEntity> explainList = handlerExplainInLinkItemDTO.getExplainList();
        FieldAttrEntity linkCompetitorField = new FieldAttrEntity();
        FieldAttrEntity linkCustomerField = new FieldAttrEntity();
        FieldAttrEntity linkOpportunityField = new FieldAttrEntity();
        for(FieldAttrEntity fieldAttrEntity :explainList) {
            if (Objects.equals(fieldAttrEntity.getAttr(), CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr())){
                fieldAttrEntity.setVisible(1);
                linkCompetitorField = fieldAttrEntity;
            }else if(Objects.equals(fieldAttrEntity.getAttr(), CompetitorAnalysisEnum.CUSTOMER_NAME_HIDE.getAttr())) {
                fieldAttrEntity.setVisible(1);
                linkCustomerField = fieldAttrEntity;
            }else if(Objects.equals(fieldAttrEntity.getAttr(), CompetitorAnalysisEnum.OPPORTUNITY_NAME_HIDE.getAttr())){
                fieldAttrEntity.setVisible(1);
                linkOpportunityField = fieldAttrEntity;
            }else if(Objects.equals(fieldAttrEntity.getAttr(), CompetitorAnalysisEnum.BASE_INFO.getAttr())){
                fieldAttrEntity.setVisible(1);
            }else if(Objects.equals(fieldAttrEntity.getAttr(), CompetitorAnalysisEnum.COMPETITIVE_INDICATORS.getAttr())){
                fieldAttrEntity.setVisible(1);
            }
        }
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(handlerExplainInLinkItemDTO.getLinkBusinessType());
        switch (redundantTemplateTypeEnum) {
            case COMPETITOR:
                String competitorName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, CompetitorEnum.NAME.getAttr(), "");
                linkCompetitorField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, competitorName));
//                linkCompetitorField.setEditable(0);
                break;
            case SALES_OPPORTUNITY:
                String opportunityName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, SalesOpportunityEnum.NAME.getAttr(), "");
                linkOpportunityField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, opportunityName));
//                linkOpportunityField.setEditable(0);

                JSONArray jsonArrayOrDefault = FastJsonHelper.getJsonArrayOrDefault(linkFormData, SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), new JSONArray());
                if(CollectionsUtil.isNotEmpty(jsonArrayOrDefault)){
                    JSONObject customerJsonObject = (JSONObject)jsonArrayOrDefault.get(0);
                    Long customerId = customerJsonObject.getLong("id");
                    String customerName = customerJsonObject.getString("name");
                    linkCustomerField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(customerId, customerName));
                }
//                linkCustomerField.setEditable(0);
            default:
                break;
        }
        // 先选客户才能再选机会
        SaasParticularAttributePoJo saasParticularAttributePoJo = new SaasParticularAttributePoJo();
        saasParticularAttributePoJo.setMultiCheck(false);
        saasParticularAttributePoJo.setRelyAttr(linkCustomerField.getAttr());
        saasParticularAttributePoJo.setRelyBusiness(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        linkOpportunityField.setSaasParticularAttributePoJo(saasParticularAttributePoJo);

    }

    @Override
    public CompetitorAnalysisListVO list(CompetitorAnalysisListDTO competitorAnalysisListDTO) throws XbbException {
        CompetitorAnalysisListVO competitorAnalysisListVO = new CompetitorAnalysisListVO();
        String corpid = competitorAnalysisListDTO.getCorpid();
        Long dataId = competitorAnalysisListDTO.getDataId();
        Integer page = competitorAnalysisListDTO.getPage();
        Integer pageSize = competitorAnalysisListDTO.getPageSize();
        Map<String, String> sortMap = competitorAnalysisListDTO.getSortMap();
        String platform = competitorAnalysisListDTO.getPlatform();
        String field = CompetitorAnalysisEnum.THREAT_INDEX.getAttr();
        String sort = "desc";
        if(sortMap!=null){
            field = sortMap.get("field");
            sort = sortMap.get("sort");
        }
        List<CompetitorAnalysisEntity> competitorAnalysisEntityList = null;
        PaasFormExplainEntity paasFormExplainEntity = null;
        Integer start = (page-1)*pageSize;
        List<FieldAttrEntity> headList = new ArrayList<>();
        // 竞争对手
        competitorAnalysisEntityList = competitorAnalysisModel.listBycondition(dataId,corpid,start,pageSize,field,sort);
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("oppotunityId",dataId);
        param.put("del",0);
        Integer count = competitorAnalysisModel.getEntitysCount(param);
        // 竞争对手分析的解释
        paasFormExplainEntity = paasFormExplainModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode(), corpid);
        if(paasFormExplainEntity==null){
            paasFormExplainEntity = paasFormExplainModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode(), "0");
        }
        // 处理成返回给前端的数据格式
        handleCompetitorAnalysisList(platform,corpid,competitorAnalysisEntityList,paasFormExplainEntity,headList);
        // 查询此机会赢单的竞争对手id
        OpportunityEntityExt opportunityEntityExt = opportunityModel.getByKey(dataId, corpid);
        JSONObject data = opportunityEntityExt.getData();
        Long stageId = data.getLong(SalesOpportunityEnum.STAGE_ID.getAttr());
        if(Objects.nonNull(stageId)){
//            SaleStageEntity saleStageEntity = saleStageModel.getByKey(stageId, corpid);
//            Integer stageEntityType = saleStageEntity.getType();
//            if(Objects.equals(stageEntityType, StageTypeEnum.FAIL_STAGE.getType())){
                Long winCompetitorId = data.getLong(SalesOpportunityEnum.WIN_COMPETITOR.getAttr());
                if(winCompetitorId!=null){
                    competitorAnalysisListVO.setWinCompetitorId(winCompetitorId);
                }
//            }
        }
        List<JSONObject> dataList = new ArrayList<>();
        competitorAnalysisEntityList.forEach(item->{
            dataList.add(item.getData());
        });
        competitorAnalysisListVO.setDataList(dataList);
        competitorAnalysisListVO.setHeadList(headList);
        PageHelper pageHelper = new PageHelper(page, pageSize);
        pageHelper.setRowsCount(count);
        competitorAnalysisListVO.setPageHelper(pageHelper);
        return competitorAnalysisListVO;
    }

    @Override
    public CompetitorAnalysisUpdateGetVO updateGet(CompetitorAnalysisUpdateGetDTO competitorAnalysisUpdateGetDTO) throws XbbException {
        CompetitorAnalysisUpdateGetVO competitorAnalysisUpdateGetVO = new CompetitorAnalysisUpdateGetVO();
        Long dataId = competitorAnalysisUpdateGetDTO.getDataId();
        String corpid = competitorAnalysisUpdateGetDTO.getCorpid();
        // 竞争对手分析数据
        CompetitorAnalysisEntity competitorAnalysisEntity = competitorAnalysisModel.getByKey(dataId, corpid);
        // 竞争对手分析解释
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode(), corpid);
        // 处理下数据返回给前端想要的格式
        handleUpdateGetCompetitorAnalysis(corpid,competitorAnalysisEntity,paasFormExplainEntity);
        String explains = paasFormExplainEntity.getExplains();
        List<FieldAttrEntity> explainList = JSONArray.parseArray(explains, FieldAttrEntity.class);
        competitorAnalysisUpdateGetVO.setData(competitorAnalysisEntity.getData());
        competitorAnalysisUpdateGetVO.setExplainList(explainList);
        return competitorAnalysisUpdateGetVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CompetitorAnalysisDeleteVO delete(CompetitorAnalysisDeleteDTO competitorAnalysisDeleteDTO) throws XbbException {
        CompetitorAnalysisDeleteVO competitorAnalysisDeleteVO = new CompetitorAnalysisDeleteVO();
        Long dataId = competitorAnalysisDeleteDTO.getDataId();
        String corpid = competitorAnalysisDeleteDTO.getCorpid();
        // 删除竞争对手分析
        CompetitorAnalysisEntity competitorAnalysisEntity = competitorAnalysisModel.getByKey(dataId, corpid);
        // 将关联的机会的字段去除此竞争对手
        Long oppotunityId = competitorAnalysisEntity.getOppotunityId();
        Long competitorId = competitorAnalysisEntity.getCompetitorId();
        OpportunityEntityExt opportunityEntityExt = opportunityModel.getByKey(oppotunityId, corpid);
        JSONObject opportunityEntityExtData = opportunityEntityExt.getData();
        JSONObject updateJsonObject = new JSONObject();
        JSONArray linkCompetitorArray = opportunityEntityExtData.getJSONArray(SalesOpportunityEnum.LINK_COMPETITOR.getAttr());
        JSONArray linkCompetitorNameArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(opportunityEntityExtData, SalesOpportunityEnum.LINK_COMPETITOR_LINK_TEXT.getAttr(), new JSONArray());
        Long winCompetitorId = opportunityEntityExtData.getLong(SalesOpportunityEnum.WIN_COMPETITOR.getAttr());
        String deleteName = null;
        if(linkCompetitorArray!=null){
            JSONArray jsonArray = new JSONArray();
            JSONArray nameJsonArray = new JSONArray();
            for(int i=0; i<linkCompetitorArray.size();i++){
                Object o = linkCompetitorArray.get(i);
                Long id = Long.parseLong(o.toString());
                if(!Objects.equals(id,competitorId)){
                    jsonArray.add(id);
                    nameJsonArray.add(linkCompetitorNameArray.get(i));
                }else{
                    deleteName = linkCompetitorNameArray.get(i).toString();
                }
            }
            updateJsonObject.put(SalesOpportunityEnum.LINK_COMPETITOR.getAttr(), jsonArray);
            updateJsonObject.put(SalesOpportunityEnum.LINK_COMPETITOR_LINK_TEXT.getAttr(), nameJsonArray);
        }
        if(winCompetitorId!=null && Objects.equals(winCompetitorId,competitorId)){
            // 此次删除的竞争对手分析中的竞争对手id是 关联机会的赢单竞争对手
            updateJsonObject.put(SalesOpportunityEnum.WIN_COMPETITOR.getAttr(), null);
            updateJsonObject.put(SalesOpportunityEnum.WIN_COMPETITOR_LINK_TEXT.getAttr(), null);
        }
        if(updateJsonObject!=null&& updateJsonObject.size()>0){
            UpdateDataEntity updateData = ExplainUtil.getUpdateData(oppotunityId, updateJsonObject, corpid);
            opportunityModel.updateBatch(Collections.singletonList(updateData), corpid);
        }
        competitorAnalysisModel.deleteByKey(dataId, corpid);

        // 取消关联关系，动态保存
        saveDynamic(corpid,competitorAnalysisDeleteDTO.getUserId(),competitorAnalysisDeleteDTO.getLoginUserName(),oppotunityId,competitorId);

        // 日志记录
        afterDeletedLog(competitorAnalysisDeleteDTO,competitorAnalysisEntity);

        return competitorAnalysisDeleteVO;
    }

    /**
     * 记录取消关联销售机会日志
     * @param competitorAnalysisDeleteDTO
     * @param competitorAnalysisEntity
     */
    private void afterDeletedLog(CompetitorAnalysisDeleteDTO competitorAnalysisDeleteDTO,CompetitorAnalysisEntity competitorAnalysisEntity){
        LinkCompetitorLogDTO linkCompetitorLogDTO = new LinkCompetitorLogDTO();
        BeanUtil.copyProperties(competitorAnalysisDeleteDTO,linkCompetitorLogDTO);
        linkCompetitorLogDTO.setCompetitorId(competitorAnalysisEntity.getCompetitorId());
        linkCompetitorLogDTO.setOpportunityId(competitorAnalysisEntity.getOppotunityId());
        CompetitorAnalysisOperationLogHandler competitorAnalysisOperationLogHandler = (CompetitorAnalysisOperationLogHandler) operationLogFactory.getOperationLogHandle(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode());
        if (Objects.nonNull(competitorAnalysisOperationLogHandler)) {
            competitorAnalysisOperationLogHandler.cancelLinkCompetitor(linkCompetitorLogDTO);
        }
    }

    @Override
    @Transactional
    public CompetitorAnalysisUpdateVO update(CompetitorAnalysisUpdateDTO competitorAnalysisUpdateDTO) throws XbbException {
        CompetitorAnalysisUpdateVO competitorAnalysisUpdateVO = new CompetitorAnalysisUpdateVO();
        String corpid = competitorAnalysisUpdateDTO.getCorpid();
        Long dataId = competitorAnalysisUpdateDTO.getDataId();
        Integer type = competitorAnalysisUpdateDTO.getType();
        JSONObject dataList = competitorAnalysisUpdateDTO.getDataList();
        // 解析下拉
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode(), corpid);
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        // 必填校验
        for(int i=0;i<explainList.size(); i++){
            FieldAttrEntity fieldAttrEntity = explainList.get(i);
            String attr = fieldAttrEntity.getAttr();
            if(attr.equals(CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr()) ||
                    attr.equals(CompetitorAnalysisEnum.CUSTOMER_NAME_HIDE.getAttr()) ||
                    attr.equals(CompetitorAnalysisEnum.OPPORTUNITY_NAME_HIDE.getAttr())
            ){
                continue;
            }
            Integer required = fieldAttrEntity.getRequired();
            if(Objects.equals(type,2)){
                if(required !=null && required==1){
                    Object value = dataList.get(attr);
                    if(value==null){
                        throw new XbbException(WorkReportErrorCodeEnum.API_ERROR_207023, WorkReportErrorCodeEnum.API_ERROR_207023.getMsg(), I18nMessageUtil.getMessage(fieldAttrEntity.getAttrName()));
                    }
                }
            }else{
                if(required !=null && required==1 && dataList.containsKey(attr)){
                    Object value = dataList.get(attr);
                    if(value==null){
                        throw new XbbException(WorkReportErrorCodeEnum.API_ERROR_207023, WorkReportErrorCodeEnum.API_ERROR_207023.getMsg(), I18nMessageUtil.getMessage(fieldAttrEntity.getAttrName()));
                    }
                }
            }

        }
        dataList.remove(CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr());
        dataList.remove(CompetitorAnalysisEnum.CUSTOMER_NAME_HIDE.getAttr());
        dataList.remove(CompetitorAnalysisEnum.OPPORTUNITY_NAME_HIDE.getAttr());
        Map<String, FieldAttrEntity> explainMap = explainList.stream().collect(Collectors.toMap(FieldAttrEntity::getAttr, Function.identity()));
        Map<String,String> requiredAttr = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        dataList.keySet().forEach(item->{
            FieldAttrEntity fieldAttrEntity = explainMap.get(item);
            if(fieldAttrEntity!=null){
                Integer noRepeat = fieldAttrEntity.getNoRepeat();
                if(Objects.equals(fieldAttrEntity.getFieldType(),FieldTypeEnum.COMBO.getType())){
                    JSONObject jsonObject = dataList.getJSONObject(fieldAttrEntity.getAttr());
                    if(Objects.nonNull(jsonObject)){
                        dataList.put(fieldAttrEntity.getAttr(),jsonObject.getString("value"));
                    }
                }
                if(noRepeat!=null && noRepeat==1){
                    requiredAttr.put(item,(String) dataList.get(item));
                }
            }
        });
        if(requiredAttr!=null && requiredAttr.size()>0){
            Long repeat = competitorAnalysisModel.repeat(corpid,dataId,requiredAttr);
            if(repeat>0){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.DUPLICATE_VALUE, "");
            }
        }
        CompetitorAnalysisEntity competitorAnalysisEntity = competitorAnalysisModel.getByKey(dataId, corpid);
        // 这里先存储老数据，用于后面的日志保存使用
        JSONObject oldData = competitorAnalysisEntity.getData();
        oldData.put("updateTime",competitorAnalysisEntity.getUpdateTime());
        if(Objects.equals(type,2)){
            // 多字段
            competitorAnalysisEntity.setData(dataList);
            competitorAnalysisModel.update(competitorAnalysisEntity);
        }else{
            // 单字段
            competitorAnalysisEntity.setData(dataList);
            competitorAnalysisModel.updateDataAttr(corpid,dataId,dataList,null);
        }
        // 这里存储新的
        JSONObject newData = (JSONObject) CloneUtil.deepClone(dataList);
        newData.put("updateTime", DateTimeUtil.getInt());
        Set<Map.Entry<String, Object>> oldEntrySet = oldData.entrySet();
        oldEntrySet.removeIf(item -> !newData.containsKey(item.getKey()));
        for (Map.Entry<String, Object> entry : newData.entrySet()) {
            String key = entry.getKey();
            oldData.put(key,oldData.get(key));
        }
        // 保存日志
        afterUpdateLog(competitorAnalysisUpdateDTO,oldData,newData,competitorAnalysisEntity,paasFormExplainEntity);
        return competitorAnalysisUpdateVO;
    }

    private void afterUpdateLog(CompetitorAnalysisUpdateDTO competitorAnalysisUpdateDTO,JSONObject oldData,JSONObject newData,CompetitorAnalysisEntity competitorAnalysisEntity,PaasFormExplainEntity paasFormExplainEntity){
        CompetitorAnalysisUpdateLogDTO competitorAnalysisUpdateLogDTO = new CompetitorAnalysisUpdateLogDTO();
        BeanUtil.copyProperties(competitorAnalysisUpdateDTO,competitorAnalysisUpdateLogDTO);
        competitorAnalysisUpdateLogDTO.setOldData(oldData);
        competitorAnalysisUpdateLogDTO.setNewData(newData);
        competitorAnalysisUpdateLogDTO.setCompetitorId(competitorAnalysisEntity.getCompetitorId());
        competitorAnalysisUpdateLogDTO.setOpportunityId(competitorAnalysisEntity.getOppotunityId());
        competitorAnalysisUpdateLogDTO.setPaasFormExplainEntity(paasFormExplainEntity);

        CompetitorAnalysisOperationLogHandler competitorOperationLogHandle = (CompetitorAnalysisOperationLogHandler) operationLogFactory.getOperationLogHandle(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode());
        if (Objects.nonNull(competitorOperationLogHandle)) {
            competitorOperationLogHandle.editCompetitorAnalysis(competitorAnalysisUpdateLogDTO);
        }
    }

    @Override
    public CompetitorAnalysisSwotGetVO swotGet(CompetitorAnalysisSwotGetDTO competitorAnalysisSwotGetDTO) throws XbbException {
        CompetitorAnalysisSwotGetVO competitorAnalysisSwotGetVO = new CompetitorAnalysisSwotGetVO();
        String corpid = competitorAnalysisSwotGetDTO.getCorpid();
        Long dataId = competitorAnalysisSwotGetDTO.getDataId();
        JSONArray swot = null;
        JSONObject data = null;
        CompetitorAnalysisEntity competitorAnalysisEntity = competitorAnalysisModel.getByKey(dataId, corpid);
        if(competitorAnalysisEntity!=null){
            swot = competitorAnalysisEntity.getSwot();
            data = competitorAnalysisEntity.getData();
        }
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode(), corpid);
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        // 不支持在swot中展示的字段
        List<String> unSupportSwotAttrList = CompetitorAnalysisEnum.getUnSupportSwotAttrList();
        // 不支持在swot中展示的字段类型
        List<Integer> unSupportSwotFieldType = CompetitorAnalysisEnum.getUnSupportSwotFieldType();
        Iterator<FieldAttrEntity> iterator = explainList.iterator();
        while(iterator.hasNext()) {
            FieldAttrEntity fieldAttrEntity = iterator.next();
            String attr = fieldAttrEntity.getAttr();
            Integer fieldType = fieldAttrEntity.getFieldType();
            if(unSupportSwotAttrList.contains(attr) || unSupportSwotFieldType.contains(fieldType)){
                iterator.remove();
            }
        }
        if(swot!=null){
            competitorAnalysisSwotGetVO.setSwot(swot);
        }
        competitorAnalysisSwotGetVO.setExplainList(explainList);
        competitorAnalysisSwotGetVO.setData(data);
        return competitorAnalysisSwotGetVO;
    }

    @Override
    public CompetitorAnalysisSwotUpdateVO swotUpdate(CompetitorAnalysisSwotUpdateDTO competitorAnalysisSwotUpdateDTO) throws XbbException {
        CompetitorAnalysisSwotUpdateVO competitorAnalysisSwotUpdateVO = new CompetitorAnalysisSwotUpdateVO();
        String corpid = competitorAnalysisSwotUpdateDTO.getCorpid();
        Long dataId = competitorAnalysisSwotUpdateDTO.getDataId();
        JSONArray swot = competitorAnalysisSwotUpdateDTO.getSwot();
        JSONObject dataList = competitorAnalysisSwotUpdateDTO.getDataList();
        // 这里先获取一下旧的swot数据，用于日志比较保存
        CompetitorAnalysisEntity oldCompetitorAnalysis = competitorAnalysisModel.getByKey(dataId, corpid);
        JSONArray oldSwot = oldCompetitorAnalysis.getSwot();

        // 更新主数据和swot数据
        competitorAnalysisModel.updateDataAttr(corpid,dataId,dataList,swot);
        // 日志保存
        afterSwotUpdateLog(competitorAnalysisSwotUpdateDTO,oldSwot,swot,oldCompetitorAnalysis);
        return competitorAnalysisSwotUpdateVO;
    }

    private void afterSwotUpdateLog(CompetitorAnalysisSwotUpdateDTO competitorAnalysisSwotUpdateDTO,JSONArray oldSwot,JSONArray newSwot,CompetitorAnalysisEntity competitorAnalysisEntity){

        SwotUpdateLogDTO swotUpdateLogDTO = new SwotUpdateLogDTO();
        BeanUtil.copyProperties(competitorAnalysisSwotUpdateDTO,swotUpdateLogDTO);
        swotUpdateLogDTO.setOldSwot(oldSwot);
        swotUpdateLogDTO.setNewSwot(newSwot);
        swotUpdateLogDTO.setCompetitorId(competitorAnalysisEntity.getCompetitorId());
        swotUpdateLogDTO.setOpportunityId(competitorAnalysisEntity.getOppotunityId());

        CompetitorAnalysisOperationLogHandler competitorOperationLogHandle = (CompetitorAnalysisOperationLogHandler) operationLogFactory.getOperationLogHandle(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode());
        if (Objects.nonNull(competitorOperationLogHandle)) {
            competitorOperationLogHandle.editSwotAnalysis(swotUpdateLogDTO);
        }

    }

    @Override
    public CompetitorAnalysisSearchListVO searchList(CompetitorAnalysisSearchListDTO competitorAnalysisSearchListDTO) throws XbbException {
        CompetitorAnalysisSearchListVO competitorAnalysisSearchListVO = new CompetitorAnalysisSearchListVO();
        String corpid = competitorAnalysisSearchListDTO.getCorpid();
        Long dataId = competitorAnalysisSearchListDTO.getDataId();

        CompetitorAnalysisEntity competitorAnalysisEntity = competitorAnalysisModel.getByKey(dataId,corpid);
        Long oppotunityId = competitorAnalysisEntity.getOppotunityId();

        Map<String,Object> params = new HashMap<>();
        params.put("corpid",corpid);
        params.put("oppotunityId",oppotunityId);
        params.put("del",0);
        List<CompetitorAnalysisEntity> competitorAnalysisEntityList = competitorAnalysisModel.findEntitys(params);

        Set<Long> competitorIdSet = new HashSet<>();
        Map<Long,CompetitorAnalysisEntity> competitorAnalysisMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        competitorAnalysisEntityList.forEach(item->{
            Long tempCompetitorId = item.getCompetitorId();
            Long tempId = item.getId();
            competitorIdSet.add(tempCompetitorId);
            competitorAnalysisMap.put(tempCompetitorId,item);
        });

        List<CompetitorEntity> competitorEntityList = competitorModel.getByKeys(competitorIdSet, corpid);

        List<CompetitorAnalysisSearchListItemPojo> competitorAnalysisSearchListItemPojoList = new ArrayList<>();
        competitorEntityList.forEach(item->{
            Long id = item.getId();
            String name = item.getData().getString(CompetitorEnum.NAME.getAttr());
            CompetitorAnalysisEntity tempEntity = competitorAnalysisMap.get(id);
            CompetitorAnalysisSearchListItemPojo pojo = new CompetitorAnalysisSearchListItemPojo(id,tempEntity.getId(),name);
            competitorAnalysisSearchListItemPojoList.add(pojo);
        });
        competitorAnalysisSearchListVO.setList(competitorAnalysisSearchListItemPojoList);
        return competitorAnalysisSearchListVO;
    }

    @Override
    public CompetitorAnalysisDetailVO detail(CompetitorAnalysisDetailDTO competitorAnalysisDetailDTO) throws XbbException {
        CompetitorAnalysisDetailVO competitorAnalysisDetailVO = new CompetitorAnalysisDetailVO();
        Long dataId = competitorAnalysisDetailDTO.getDataId();
        String corpid = competitorAnalysisDetailDTO.getCorpid();
        // 竞争对手分析数据
        CompetitorAnalysisEntity competitorAnalysisEntity = competitorAnalysisModel.getByKey(dataId, corpid);
        // 竞争对手分析解释
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode(), corpid);
        // 处理下数据返回给前端想要的格式
        handleDetailCompetitorAnalysis(corpid,competitorAnalysisEntity,paasFormExplainEntity);
        String explains = paasFormExplainEntity.getExplains();
        List<FieldAttrEntity> explainList = JSONArray.parseArray(explains, FieldAttrEntity.class);
        competitorAnalysisDetailVO.setData(competitorAnalysisEntity.getData());
        competitorAnalysisDetailVO.setExplainList(explainList);
        return competitorAnalysisDetailVO;
    }

    /**base
     * 处理数据，返回前端想要的格式
     * date: 2022/8/26 10:11 上午
     * @author yingjf
     * @param competitorAnalysisEntityList: 竞争对手列表
     * @param paasFormExplainEntity: 解释
     */
    private void handleCompetitorAnalysisList(String platform,String corpid,List<CompetitorAnalysisEntity> competitorAnalysisEntityList,PaasFormExplainEntity paasFormExplainEntity,List<FieldAttrEntity> headList)throws XbbException{
        Set<Long> competitorIdSet = new HashSet<>();
        competitorAnalysisEntityList.forEach(item->{
            Long competitorId = item.getCompetitorId();
            competitorIdSet.add(competitorId);
        });
        List<CompetitorEntity> competitorEntityList = competitorModel.getByKeys(competitorIdSet, corpid);
        Map<Long,CompetitorEntity> competitorMap = new HashMap<>(competitorEntityList.size());
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains());
        competitorEntityList.forEach(item->{
            competitorMap.put(item.getId(),item);
        });
        competitorAnalysisEntityList.forEach(item->{
            JSONObject data = item.getData();
            Long competitorId = item.getCompetitorId();
            CompetitorEntity competitorEntity = competitorMap.get(competitorId);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dataId",competitorId);
            jsonObject.put("formId",competitorEntity.getFormId());
            jsonObject.put("businessType",XbbRefTypeEnum.COMPETITOR.getCode());
            jsonObject.put("saasMark", SaasMarkEnum.SAAS.getCode());
            jsonObject.put("name", competitorEntity.getData().getString(CustomerManagementEnum.NAME.getAttr()));
            data.put(CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr(),jsonObject);
            for(String key: data.keySet()){
                FieldAttrEntity fieldAttrEntity = explainMap.get(key);
                if(fieldAttrEntity==null){
                    continue;
                }
                Integer fieldType = fieldAttrEntity.getFieldType();
                if(Objects.equals(fieldType,FieldTypeEnum.COMBO.getType())){
                    String uuidValue = data.getString(key);
                    List<ItemPoJo> items = fieldAttrEntity.getItems();
                    Map<String,String> itemsMap = new HashMap<>();
                    List<ItemPoJo> itemPoJos = fieldAttrEntity.getItems();
                    //其他选项
                    boolean isOther = false;
                    for (ItemPoJo itemPoJo : itemPoJos) {
                        if (Objects.equals(1, itemPoJo.getIsOther())) {
                            isOther = true;
                        }
                    }
                    items.forEach(i-> itemsMap.put(i.getValue().toString(), i.getText()));
                    String text = itemsMap.get(uuidValue);
                    if(text !=null){
                        // 因为可能会有其它
                        data.put(key,text);
                    }else{
                        if(!isOther){
                            data.put(key,null);
                        }
                    }
                }
            }
            data.put("id",item.getId());
        });
        List<FieldAttrEntity> showFieldAttrEntityList = new ArrayList<>();
        // 移动端和web端不太一样，移动端有个详情页的，不需要过滤
        List<Integer> invisibleFieldList = new ArrayList<>();
        if(Objects.equals(platform, PlatFormEnum.WEB.getValue())){
            invisibleFieldList = Arrays.asList(FieldTypeEnum.SEPARATOR.getType(),FieldTypeEnum.LINK_BUSINESS_SINGLE.getType(),FieldTypeEnum.LINK_BUSINESS_MULTI.getType());
        }
        List<Integer> finalInvisibleFieldList = invisibleFieldList;
        explainList.forEach(item->{
            Integer fieldType = item.getFieldType();
            String attr = item.getAttr();
            Integer isOpen = item.getIsOpen();
            if(!Objects.equals(isOpen, BasicConstant.ONE)){
                return;
            }
            if(Objects.equals(attr,CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr())){

            }else{
                if(finalInvisibleFieldList.contains(fieldType)){
                    return;
                }
            }
            showFieldAttrEntityList.add(item);
        });

        headList.addAll(showFieldAttrEntityList);
        paasFormExplainEntity.setExplains(JSON.toJSONString(showFieldAttrEntityList));
    }

    /**
     * 处理竞争对手分析数据
     * date: 2022/8/26 3:37 下午
     * @author yingjf
     * @param competitorAnalysisEntity:
     */
    private void handleUpdateGetCompetitorAnalysis(String corpid,CompetitorAnalysisEntity competitorAnalysisEntity,PaasFormExplainEntity paasFormExplainEntity){
        Long customerId = competitorAnalysisEntity.getCustomerId();
        Long oppotunityId = competitorAnalysisEntity.getOppotunityId();
        Long competitorId = competitorAnalysisEntity.getCompetitorId();
        JSONObject data = competitorAnalysisEntity.getData();

        String explains = paasFormExplainEntity.getExplains();
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explains, "");

        // 处理下字段不可编辑
        explainMap.forEach((attr,fieldAttrEntity)->{
            if(Objects.equals(attr,CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr())
                ||Objects.equals(attr,CompetitorAnalysisEnum.CUSTOMER_NAME_HIDE.getAttr())
                ||Objects.equals(attr,CompetitorAnalysisEnum.OPPORTUNITY_NAME_HIDE.getAttr())){
                fieldAttrEntity.setEditable(0);
                fieldAttrEntity.setVisible(1);
            }
            if(Objects.equals(fieldAttrEntity.getFieldType(),FieldTypeEnum.COMBO.getType())){
                String uuidValue = data.getString(attr);
                List<ItemPoJo> items = fieldAttrEntity.getItems();
                //其他选项
                boolean isOther = false;
                for (ItemPoJo itemPoJo : items) {
                    if (Objects.equals(1, itemPoJo.getIsOther())) {
                        isOther = true;
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("text",uuidValue);
                        jsonObject.put("value",uuidValue);
                        data.put(attr,jsonObject);
                    }
                }
                items.forEach(item->{
                    Object value = item.getValue();
                    String text = item.getText();
                    if(Objects.equals(value,uuidValue)){
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("text",text);
                        jsonObject.put("value",value.toString());
                        data.put(attr,jsonObject);
                    }
                });
            }

        });

        // 处理客户id
        CustomerEntityExt customerEntityExt = customerModel.getByKey(customerId, corpid);
        if(customerEntityExt!=null){
            String customerName = customerEntityExt.getData().getString(CustomerManagementEnum.NAME.getAttr());
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name",customerName);
            jsonObject.put("id",customerId);
            jsonArray.add(jsonObject);
            data.put(CompetitorAnalysisEnum.CUSTOMER_NAME_HIDE.getAttr(), jsonArray);
        }
        // 处理机会id
        OpportunityEntityExt opportunityEntityExt = opportunityModel.getByKey(oppotunityId, corpid);
        if(customerEntityExt!=null){
            String opportunityName = opportunityEntityExt.getData().getString(SalesOpportunityEnum.NAME.getAttr());
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name",opportunityName);
            jsonObject.put("id",oppotunityId);
            jsonArray.add(jsonObject);
            data.put(CompetitorAnalysisEnum.OPPORTUNITY_NAME_HIDE.getAttr(), jsonArray);
        }

        // 处理竞争对手id
        CompetitorEntity competitorEntity = competitorModel.getByKey(competitorId, corpid);
        if(competitorEntity!=null){
            String competitorName = competitorEntity.getData().getString(CompetitorEnum.NAME.getAttr());
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name",competitorName);
            jsonObject.put("id",oppotunityId);
            jsonArray.add(jsonObject);
            data.put(CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr(), jsonArray);
        }

        paasFormExplainEntity.setExplains(JSON.toJSONString(explainMap.values()));
    }

    /**
     * 处理竞争对手分析数据-详情使用
     * date: 2022/8/26 3:37 下午
     * @author yingjf
     * @param competitorAnalysisEntity:
     */
    private void handleDetailCompetitorAnalysis(String corpid,CompetitorAnalysisEntity competitorAnalysisEntity,PaasFormExplainEntity paasFormExplainEntity){
        Long customerId = competitorAnalysisEntity.getCustomerId();
        Long oppotunityId = competitorAnalysisEntity.getOppotunityId();
        Long competitorId = competitorAnalysisEntity.getCompetitorId();
        JSONObject data = competitorAnalysisEntity.getData();

        String explains = paasFormExplainEntity.getExplains();
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explains, "");

        // 处理下字段不可编辑
        explainMap.forEach((attr,fieldAttrEntity)->{
            if(Objects.equals(attr,CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr())
                    ||Objects.equals(attr,CompetitorAnalysisEnum.CUSTOMER_NAME_HIDE.getAttr())
                    ||Objects.equals(attr,CompetitorAnalysisEnum.OPPORTUNITY_NAME_HIDE.getAttr())){
                fieldAttrEntity.setEditable(0);
                fieldAttrEntity.setVisible(1);
            }
            if(fieldAttrEntity.getIsOpen()!=1){
                fieldAttrEntity.setVisible(0);
            }
            if(Objects.equals(fieldAttrEntity.getFieldType(),FieldTypeEnum.COMBO.getType())){
                String uuidValue = data.getString(attr);
                List<ItemPoJo> items = fieldAttrEntity.getItems();
                items.forEach(item->{
                    Object value = item.getValue();
                    String text = item.getText();
                    if(Objects.equals(value,uuidValue)){
                        data.put(attr,text);
                    }
                });
            }

        });

        // 处理客户id
        CustomerEntityExt customerEntityExt = customerModel.getByKey(customerId, corpid);
        if(customerEntityExt!=null){
            String customerName = customerEntityExt.getData().getString(CustomerManagementEnum.NAME.getAttr());
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name",customerName);
            jsonObject.put("id",customerId);
            jsonArray.add(jsonObject);
            data.put(CompetitorAnalysisEnum.CUSTOMER_NAME_HIDE.getAttr(), jsonArray);
        }
        // 处理机会id
        OpportunityEntityExt opportunityEntityExt = opportunityModel.getByKey(oppotunityId, corpid);
        if(customerEntityExt!=null){
            String opportunityName = opportunityEntityExt.getData().getString(SalesOpportunityEnum.NAME.getAttr());
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name",opportunityName);
            jsonObject.put("id",oppotunityId);
            jsonArray.add(jsonObject);
            data.put(CompetitorAnalysisEnum.OPPORTUNITY_NAME_HIDE.getAttr(), jsonArray);
        }

        // 处理竞争对手id
        CompetitorEntity competitorEntity = competitorModel.getByKey(competitorId, corpid);
        if(competitorEntity!=null){
            String competitorName = competitorEntity.getData().getString(CompetitorEnum.NAME.getAttr());
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name",competitorName);
            jsonObject.put("id",competitorId);
            jsonArray.add(jsonObject);
            data.put(CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr(), jsonArray);
        }

        paasFormExplainEntity.setExplains(JSON.toJSONString(explainMap.values()));
    }

    /**
     * 删除竞争对手分析时，保存取消关联关系动态
     * @param coripId
     * @param userId
     * @param opportunityId
     */
    private void saveDynamic(String coripId, String userId ,String userName,Long opportunityId,Long competitorId){
        DynamicLinkOpportunityDTO dynamicLinkOpportunityDTO = new DynamicLinkOpportunityDTO();
        dynamicLinkOpportunityDTO.setOpportunityId(opportunityId);
        dynamicLinkOpportunityDTO.setUserId(userId);
        dynamicLinkOpportunityDTO.setCorpid(coripId);
        dynamicLinkOpportunityDTO.setCompetitorId(competitorId);
        dynamicLinkOpportunityDTO.setUserName(userName);


        CompetitorDynamicStrategy competitorDynamicStrategy = dynamicStrategyFactory.getCompetitorDynamicstrategyByBusinessType(XbbRefTypeEnum.COMPETITOR.getCode());
        competitorDynamicStrategy.cancelOpportunity(dynamicLinkOpportunityDTO);

    }
}
